﻿using EmbeddedSharp.Core;

namespace EmbeddedSharp.Scripting {
    public class DefaultUnaryFunctionFactory : IUnaryFunctionFactory {

        public IContext Context {
            get;
            set;
        }

        public DefaultUnaryFunctionFactory(IContext context) {
            this.Context = context;
        }

        public virtual UnaryFunctionTranslator CreateTranslator(string subject) {
            return new UnaryFunctionTranslator(
                this.Context.GetFunctionManager(), subject);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="funMgr"></param>
        /// <param name="subject"></param>
        /// <returns></returns>
        public IUnaryParameterFunction Create(string var, string expr) {
            ExpressionParser parser = this.Context.GetParserFactory().CreateParser(expr);
            Node root = parser.Parse();

            return this.Create(var, root);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="var"></param>
        /// <param name="root"></param>
        /// <returns></returns>
        public IUnaryParameterFunction Create(string var, Node root)
        {
            UnaryFunctionTranslator uft = CreateTranslator(var);
            string fexpr = uft.Translate(root);

            CSharpFunctionCompiler csharpfc
                = new CSharpFunctionCompiler();
            IUnaryParameterFunction func = csharpfc.Parse(fexpr);

            return func;
        }
    }
}
